<html>
  <head></head>
  <body>
    <div>
      <p>递归深拷贝</p>
    </div>
    <script>
      var arr = [1, 2, 3, [4, 5], [6, 7, [8, 9]]]
      var obj = {
        name: 'burc',
        age: [21, 22],
        myfn: function () {
          console.log('我是一个函数')
        },
      }
      var str = 'love'

      var cloneArr = deepClone(arr)
      var cloneObj = deepClone(obj)
      var cloneStr = deepClone(str)

      cloneArr[0] = 81
      cloneArr[4][2][0] = 88
      cloneObj['name'] = 'vinx'
      cloneObj['age'][0] = 22

      cloneObj.myfn()
      console.log(arr) // [1,2,3,[4,5],[6,7,[8,9]]]
      console.log(cloneArr) // [81,2,3,[4,5],[6,7,[88,9]]]
      console.log(obj) // {name: "burc", age: [21,22], myfn:f}
      console.log(cloneObj) // {name: "vinx", age: [22,22], myfn:f}
      console.log(cloneStr) // love

      // 深拷贝方法
      function deepClone(source) {
        // 如果是基本类型，直接返回
        if (typeof source !== 'object' || !source) return source

        const cloneTarget = source instanceof Array ? [] : {}

        // 如果是数组
        if (source instanceof Array)
          source.forEach((item, index) => (cloneTarget[index] = deepClone(item)))

        // 如果是对象
        for (const key in source) {
          if (source.hasOwnProperty(key)) cloneTarget[key] = deepClone(source[key])
        }
        
        return cloneTarget
      }
    </script>
  </body>
</html>
